import createApp from './main'
import { setApiParams } from 'jindai-api';

export default (context) => {
  return new Promise(async (resolve, reject) => {
    const { app, router, store } = createApp()
    let { url, request } = context
    setApiParams(request)

    await store.dispatch('home/fetchSetting');
    const { repair, title, keywords, description } = store.state.home.setting

    if (url === '/repair') {
      if (!repair) {
        return reject({ url: '/' });
      }
    } else {
      if (repair) {
        return reject({ url: '/repair' });
      }
    }
    context.title = title
    context.keywords = keywords
    context.description = description

    const { route } = router.resolve(url);
    const requiresAuth = route.matched.some(record => record.meta.requiresAuth);
    try {
      await store.dispatch('login/profile');
    } catch (err) {
      if (requiresAuth) {
        return reject({ url: '/' });
      }
    }

    await store.dispatch('home/fetchCates');

    router.push(url)
    return router.onReady(() => {
      const matchedComponents = router.getMatchedComponents()
      if (!matchedComponents.length) {
        return reject({ url: 404 })
      }
      setApiParams(request)
      return Promise.all(matchedComponents.map(({ asyncData }) => asyncData && asyncData({
        store,
        route: router.currentRoute
      }))).then(() => {
        context.state = store.state
        setApiParams(request)
        return resolve(app)
      }).catch((err) => {
        if (err.url) {
          return reject(err)
        } else if (err.response) {
          if (err.response.status === 401) {
            return reject({ url: '/' })
          } else if (err.response.status === 403) {
            context.state = store.state
            return resolve(app)
          } else if (err.response.status === 404) {
            return reject({ url: '/404' })
          } else if (err.response.status === 429) {
            return reject({ url: '/control-freq' })
          } else if (err.response.status >= 500) {
            return reject({ url: '/error' })
          }
        }
        return reject({ url: 'error' })
      })
    }, reject)
  })
}
